<template>
  <div>
    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <!-- 上拉加载更多 -->
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :immediate-check="false"
      >
        <!-- 循环渲染文章的列表 -->
        <ArtItem
          v-for="item in artlist"
          :key="item.art_id.toString()"
          :article="item"
          @remove-article="removeArticle"
        >
        </ArtItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArtItem from "@/components/ArtItem";
import { getArtListAPI } from "@/api/homeAPI";
export default {
  name: "ArtList",
  data() {
    return {
      artlist: [],
      timestamp: Date.now(),
      loading: false,
      finished: false,
      isLoading: false,
    };
  },
  props: {
    // 频道id（小驼峰命名：第一个单词全部小写，后面单词首字母大写）
    channelId: {
      type: Number,
      required: true,
    },
  },
  components: {
    ArtItem,
  },
  methods: {
    // 初始化文章的列表数据
    async initArtList(isRefresh) {
      // 请求API接口
      const { data: res } = await getArtListAPI(this.channelId, this.timestamp);
      if (res.message === "OK") {
        this.timestamp = res.data.pre_timestamp;
        if (isRefresh) {
          // 下拉刷新
          // "新数据在前"，旧数据在后
          this.artlist = [...res.data.results, ...this.artlist];
          // 重置isloading为false
          this.isLoading = false;
        } else {
          // 上拉加载
          // 旧数据在前，新数据在后
          this.artlist = [...this.artlist, ...res.data.results];
          // 重置loading为false
          this.loading = false;
        }
        // 判断所有的数据是否已经加载完毕
        if (res.data.pre_timestamp === null) {
          this.finished = true;
        }
      }
    },
    onLoad() {
      console.log("触发了上拉加载更多");
      this.initArtList();
    },
    onRefresh() {
      this.initArtList(true);
    },
    removeArticle(id) {
      this.artlist = this.artlist.filter(
        (item) => item.art_id.toString() !== id
      );
      // 2. 判断剩余数据的文章数量是否小于 10
      if (this.artlist.length < 10) {
        // 主动请求下一页的数据
        this.initArtList();
      }
    },
  },
  created() {
    this.initArtList();
  },
};
</script>

<style lang="less" scoped>
</style>
